import { message, Progress } from 'antd'
import { Modal, Input } from 'antd'
import React, { useState } from 'react'
import { useEffect } from 'react'
import { useRef } from 'react'
import { useCallback } from 'react'
import MyCard from '../../components/MyCard'
import { Add } from '../../components/MyIcon'
import PlanItem from '../../components/PlanItem'
import axios from 'axios'
import './index.css'
import { useNavigate } from 'react-router-dom'
import StudyRecord from '../../components/StudyRecord'
import { Cascader } from 'antd'
import { useMemo } from 'react'

const myData = [
  { key: 0, chosen: true, content: 'HTML', percent: 75 },
  { key: 1, chosen: true, content: 'JavaScript', percent: 55 },
  { key: 2, chosen: false, content: 'Java', percent: 50 },
  { key: 3, chosen: true, content: 'CSS', percent: 85 },
  { key: 4, chosen: false, content: 'Golang', percent: 85 }
]

const optionLists = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    isLeaf: false
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    isLeaf: false
  }
]

const DailyPlan = () => {
  let myInput = ''
  const navigate = useNavigate()
  const [options, setOptions] = useState(optionLists)
  const [data, setData] = useState(myData)
  const [modal, contextHolder] = Modal.useModal()

  // 总进度，需要进行计算
  const [totProcess, setTotProcess] = useState(100)

  const [curTot, setCurTot] = useState(0)

  const info = JSON.parse(localStorage.getItem('info'))
  useEffect(() => {
    console.log(info)
    if (!info) {
      modal.error({
        title: '权限错误!',
        content: '当前用户未登录，请先前往登录界面登录',
        onOk: () => {
          navigate('/center/login')
        }
      })
      return
    }
    // 请求列表数据
    axios({
      method: 'get',
      url: 'http://10.162.231.164:3000/api/dailyTask/',
      params: {
        user_mail: info.email
      }
    })
      .then(res => {
        // 清洗数据
        // 获取打卡记录
        let clockData = JSON.parse(localStorage.getItem('clockData'))
        const date = new Date()
        if (clockData === null || clockData.clockDate !== `${date.getMonth()} ${date.getDate()}`) {
          clockData = {
            clockDate: `${date.getMonth()} ${date.getDate()}`,
            clockSet: new Set()
          }
          localStorage.setItem(
            'clockData',
            JSON.stringify({
              clockDate: `${date.getMonth()} ${date.getDate()}`,
              clockSet: []
            })
          )
        }
        // 暂时转化为集合存储
        clockData.clockSet = new Set(clockData.clockSet)

        let cur = 0
        const realData = []
        res.data.forEach(item => {
          cur += parseInt(parseFloat(item.process) * 100)
          realData.push({
            key: item.tech_id,
            percent: parseInt(parseFloat(item.process) * 100),
            content: item.tech_name,
            chosen: clockData.clockSet.has(item.tech_name) // 学习计划
          })
        })
        console.log(cur)
        setCurTot(cur)
        setTotProcess(res.data.length * 100)
        setData(realData)
        // 在这里获取所有的数据，假设这里的数据是正确的格式，存储为列表
      })
      .catch(err => {
        console.log(err)
      })

    axios({
      method: 'post',
      url: 'http://10.162.231.164:3000/api/dailyTask/listAll',
      params: {
        user_mail: info.email
      }
    })
      .then(res => {
        console.log(res)
        const option = []
        res.data.forEach(item => {
          if (data.filter(it => it.content === item.tech_name).length === 0) {
            option.push({
              value: item.tech_name,
              label: item.tech_name,
              isLeaf: true
            })
          }
        })
        setOptions(option)
      })
      .catch(err => {})
  }, [])

  const choose = id => {
    const target = data.filter(item => {
      return item.key === id
    })[0]
    const tech_name = target.content

    if (target.percent >= 100) {
      message.error({
        content: '该任务已完成，打卡无效',
        duration: 1
      })
      return
    }
    if (target.chosen === true) {
      message.error({
        content: '该任务今天已经打卡了哦',
        duration: 1
      })
      return
    }
    axios({
      method: 'post',
      url: 'http://10.162.231.164:3000/api/dailyCheck',
      params: {
        tech_name,
        user_mail: info.email
      }
    })
      .then(res => {
        console.log(res)
        const clockData = JSON.parse(localStorage.getItem('clockData'))
        clockData.clockSet.push(tech_name)
        localStorage.setItem('clockData', JSON.stringify(clockData))

        // 保证此处非空
        let clockTimes = new Set(JSON.parse(localStorage.getItem('clockTimes')))
        const date = new Date()
        clockTimes.add(`${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`)
        localStorage.setItem('clockTimes', JSON.stringify([...clockTimes]))
        setData(
          data.map(item => {
            if (item.key === id) {
              item.chosen = !item.chosen
              item.percent += 10
            }
            return item
          })
        )
        setCurTot(prev => prev + 10)
        message.success({
          content: '打卡成功',
          duration: 1
        })
      })
      .catch(err => {
        console.log(err)
        message.error({
          content: '打卡失败',
          duration: 1
        })
      })
  }

  const myDelete = useCallback(
    id => {
      const curItem = data.filter(item => {
        return item.key === id
      })[0]
      axios({
        method: 'post',
        url: 'http://10.162.231.164:3000/api/dailyTask/delete',
        params: {
          tech_name: curItem.content,
          user_mail: info.email
        }
      })
        .then(res => {
          message.success({
            content: '删除成功',
            duration: 1
          })
          setData(data.filter(item => item.content !== curItem.content))
          setCurTot(prev => prev - curItem.percent)
          setTotProcess(prev => prev - 100)
          // 在这里获取所有的数据，假设这里的数据是正确的格式，存储为列表
        })
        .catch(err => {
          console.log(err)
          message.error({
            content: '删除失败',
            duration: 1
          })
        })

      setData(
        data.filter(item => {
          return item.key !== id
        })
      )
    },
    [data, setData]
  )

  const onOk = f => {
    if (data.filter(item => myInput.toLowerCase() === item.content.toLowerCase()).length) {
      message.error({
        content: '目标计划已存在',
        duration: 1
      })
      return
    }
    console.log('myInput', myInput)
    axios({
      method: 'post',
      url: 'http://10.162.231.164:3000/api/dailyTask/insert',
      params: {
        tech_name: myInput,
        user_mail: info.email
      }
    })
      .then(res => {
        console.log(res)
        data.push({ key: res.data.tech_id, chosen: false, content: myInput, percent: 0 })

        setData([...data])

        message.success({
          content: '添加成功',
          duration: 1
        })
        setOptions(prev => {
          return prev.filter(item => {
            return item.label !== myInput
          })
        })
      })
      .catch(err => {
        console.log(err)
        message.error({
          content: '添加失败',
          duration: 1
        })
      })

    f()
  }

  const onChange = (value, selectedOptions) => {
    myInput = value[0]
    console.log('触发了', myInput)
  }
  const onClick = () => {
    const config = {
      title: '新增计划',
      content: <Cascader options={options} onChange={onChange} changeOnSelect />,
      onOk
    }
    modal.confirm(config)
  }

  return (
    <>
      <div className="DailyPlan">
        <MyCard style={{ flex: '1' }}>
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              width: '520px'
            }}
          >
            <div className="DailyPlan_total" style={{ margin: '10px' }}>
              <svg width="32" height="37" viewBox="0 0 32 37" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M11.3786 0.390229C11.9357 -0.137311 12.8 -0.130084 13.3571 0.397455C15.3286 2.26913 17.1786 4.28535 18.9071 6.46777C19.6929 5.42714 20.5857 4.29257 21.55 3.36757C22.1143 2.83281 22.9857 2.83281 23.55 3.3748C26.0214 5.75956 28.1143 8.91035 29.5857 11.9021C31.0357 14.8506 32 17.8641 32 19.9887C32 29.2098 24.8714 37 16 37C7.02857 37 0 29.2025 0 19.9814C0 17.2064 1.27143 13.8172 3.24286 10.4641C5.23571 7.06035 8.05 3.5121 11.3786 0.390229ZM16.1214 30.0625C17.9286 30.0625 19.5286 29.5566 21.0357 28.5449C24.0429 26.4203 24.85 22.1711 23.0429 18.8324C22.8429 18.4277 22.6429 18.023 22.3429 17.6184L18.7286 21.8676C18.7286 21.8676 12.9143 14.3809 12.5071 13.875C9.50714 17.6184 8 19.743 8 22.1711C8 27.1285 11.6143 30.0625 16.1214 30.0625Z"
                  fill="#FF6741"
                />
              </svg>
              <Progress percent={((curTot / totProcess) * 100).toFixed(2)} />
            </div>
            {data.map(item => {
              return <PlanItem key={item.key} item={item} choose={choose} delete={myDelete}></PlanItem>
            })}
            {/* 不能增加列表，如果做了这个功能现有后端逻辑会报错 */}
            <div className="DailyPlan_addPlanItem">
              <div onClick={onClick}>
                <Add />
              </div>
            </div>
            {contextHolder}
          </div>
        </MyCard>
        {/* 学习记录 */}
        <StudyRecord />
      </div>
    </>
  )
}

export default React.memo(DailyPlan)
